package com.cybertron.ironhide.manage.action;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.cybertron.ironhide.manage.common.base.BaseAction;
import com.cybertron.ironhide.manage.domain.Category;
import com.cybertron.ironhide.manage.domain.Tag;
import com.cybertron.ironhide.manage.service.CategoryService;
import com.cybertron.ironhide.manage.service.TagService;
import com.cybertron.ironhide.manage.util.JsonUtil;

public class TagAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 364691247485463901L;

	@Resource
	private TagService tagService;

	@Resource
	private CategoryService categoryService;

	private Tag tag;

	private List<Tag> tags;

	private List<Category> categories;

	private File tagFile;

	private String tagFileFileName;

	public String list() {
		tags = tagService.selectBySelective(tag, pager);
		return LIST;
	}

	public String add() {
		categories = categoryService.selectByLevel(2);
		return ADD;
	}

	public String doAdd() {
		tagService.insertSelective(tag);
		return ajaxSuccess("添加成功", "tag-list", null, CLOSE_CURRENT);
	}

	public String doAddByFile() {
		String extension = StringUtils.substringAfterLast(tagFileFileName, ".");
		if (!"xlsx".equals(extension.toLowerCase())
				&& !"xls".equals(extension.toLowerCase())) {
			return ajaxError("上传文件格式错误", null, null, CLOSE_CURRENT);
		}
		tagService.insertSelective(tag, tagFile);
		return ajaxSuccess("添加成功", "tag-list", null, CLOSE_CURRENT);
	}

	public String file() {
		return "file";
	}

	public String edit() {
		categories = categoryService.selectByLevel(2);
		tag = tagService.selectByPrimaryKey(tag.getId());
		return EDIT;
	}

	public String doEdit() {
		tagService.updateByPrimaryKeySelective(tag);
		return ajaxSuccess("修改成功", "tag-list", null, CLOSE_CURRENT);
	}

	public String delete() {
		tagService.deleteByPrimaryKey(tag.getId());
		return ajaxSuccess("删除成功", "tag-list");
	}

	public String suggest() {
		List<Map<String, String>> result = categoryService.selectSuggest(
				StringUtils.lowerCase(q), limit);
		return ajax(JsonUtil.writeValueAsString(result), "text/x-json");
	}

	public String build() {
		tagService.buildTag();
		return ajaxSuccess("生成成功", "tag-list");
	}

	public Tag getTag() {
		return tag;
	}

	public void setTag(Tag tag) {
		this.tag = tag;
	}

	public List<Tag> getTags() {
		return tags;
	}

	public void setTags(List<Tag> tags) {
		this.tags = tags;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}

	public File getTagFile() {
		return tagFile;
	}

	public void setTagFile(File tagFile) {
		this.tagFile = tagFile;
	}

	public String getTagFileFileName() {
		return tagFileFileName;
	}

	public void setTagFileFileName(String tagFileFileName) {
		this.tagFileFileName = tagFileFileName;
	}

}
